@COFE ?= {}

$ = jQuery
Entry = COFE.Entry
EntryItem = COFE.EntryItem
EntryList = COFE.EntryList
HierarchyItem = COFE.HierarchyItem
EntryItemListBase = COFE.EntryItemListBase
utils = COFE.utils
Link = COFE.Link

class HierarchyItemList extends Spine.Controller  
  constructor : () ->
    super

  elements : 
    "#entryHierarchyList" : "treelist"    
    ".open" : "btnOpen"
    ".up" : "btnUp"

  
  init : ->      
    @App.bind("pathChanged", @onPathChanged)    

    
    @btnOpen.click( () =>
      history.back();      
    )

    @btnUp.click ( () =>
      if (@App.path.rel is "folder")
        path = utils.extractFilepath(@App.path.param)
        if (path isnt undefined)
          @App.changePath(path)
    )
    
  onPathChanged : (sender, path) =>
    @changePath(path)      

  changePath : (path) =>
    @hierarchy = @buildHierarchy(path)  
    #console.log @hierarchy
    @render()

  addOne : (path) =>    
    @idx++
    ele = $("<select></select>").attr("id", @idx).attr("name", @idx)    
    
    newItem = HierarchyItem.init({ 
      path : path      
      el : ele
      childElementKey : "<option>"      
      childTemplateKey : "#hierarchyItemTemplate"      
      App : @App 
    })    

    emptyOption = $("<option>")
    emptyOption.attr("value", path)
    if @App.path is path
      emptyOption.attr("selected", "selected")
    newItem.el.append(emptyOption)
        
    @treelist.append(newItem.el)                 
    newItem.fetch()   
    newItem.el.trigger('create')     

  buildHierarchy : (path) =>              
    #path.param = "{TEMP}/demo"          
    if path.rel isnt "folder"
      return [""]
    
    return (while path isnt undefined                  
      retVal = path
      path = Link.extractLinkpath(path)
      retVal
      ).reverse()
  
  fetch : =>            
    @changePath(@App.path)

  render : =>
    @remove()
    for path in @hierarchy   
      #console.log path   
      @addOne(path)   
       
    @trigger("rendered", @)


  remove: =>       
    @treelist.empty()  
    @idx = 0

COFE.HierarchyItemList = HierarchyItemList